﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;
using MySql.Data.MySqlClient;

namespace IronSuit.DataMap
{
	public class DBFactory : IDisposable
	{
		IDBFactory dbf;
		public DBFactory()
		{
			ConnectionStringSettings connStr = ConfigurationManager.ConnectionStrings["Default"];
			if (connStr.ProviderName.Equals("MySQLProv"))
				dbf = new MySqlFactory();
			else
				dbf = new MSDBFactory();
		}
		public DBFactory(string connKey)
		{
			ConnectionStringSettings connStr = ConfigurationManager.ConnectionStrings[connKey];
			if (connStr.ProviderName.Equals("MySQLProv"))
				dbf = new MySqlFactory(connKey);
			else
				dbf = new MSDBFactory(connKey);
		}
		public DBFactory(DbConnection conn)
		{
			if (conn is MySqlConnection)
				dbf = new MySqlFactory(conn);
			else
				dbf = new MSDBFactory(conn);
		}

		#region IDisposable Members

		public void Dispose()
		{
			((IDisposable)dbf).Dispose();
		}

		#endregion

		public void Close()
		{
			((IDisposable)dbf).Dispose();
		}
		public int ExecSql(string Sql)
		{
			return dbf.ExecSql(Sql, new List<DbParameter>());
		}
		public int ExecSql(string Sql, List<DbParameter> ParaList)
		{
			return dbf.ExecSql(Sql, ParaList);
		}
		public DataSet ExecQuerySql(string Sql)
		{
			return dbf.ExecQuerySql(Sql, new List <DbParameter >());
		}
		public DataSet ExecQuerySql(string Sql, List<DbParameter> ParaList)
		{
			return dbf.ExecQuerySql(Sql, ParaList);
		}
		public bool Insert(DataEntity Entity)
		{
			Entity.GetDataHandler().PreInsert();
			return dbf.Insert(Entity);
		}
		public bool Update(DataEntity Entity)
		{
			Entity.GetDataHandler().PreUpdata();
			return dbf.Update(Entity);
		}

		public bool Delete(DataEntity Entity)
		{
			return dbf.Delete(Entity);
		}
		public bool Query(DataEntity Entity)
		{
			return dbf.Query(Entity);
		}
		public bool QueryByField(DataEntity Entity)
		{
			List<DataEntity> ls= dbf.QueryList(Entity, 1);
			if (ls.Count > 0)
			{
				Entity.Displace(ls[0]);
				return true;
			}
			else
				return false;
		}
		public List<DataEntity> QueryList(DataEntity Entity)
		{
			return dbf.QueryList(Entity,100);
		}
		public List<DataEntity> QueryList(DataEntity Entity,int pageSize)
		{
			return dbf.QueryList(Entity, pageSize);
		}
		public long Count(DataEntity Entity)
		{
			return dbf.Count(Entity);
		}
	}
}
